<template>
  <el-main>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>{{ breadcrumbNameP }}</el-breadcrumb-item>
      <el-breadcrumb-item>{{ breadcrumbName }}</el-breadcrumb-item>
    </el-breadcrumb>
    <el-form :inline="true" :model="formInline" class="el-form query-form el-form--label-right el-form--inline">
      <el-form-item label="司机姓名">
        <el-input size="small" v-model="formInline.driver_name" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="所属DC">
        <el-select size="small" v-model="formInline.dept_id" placeholder="请选择" filterable>
          <el-option label="全部" value=""></el-option>
          <el-option v-for="item in deptData" :key="item.id" :value="item.id" :label="item.title">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="联系方式">
        <el-input size="small" v-model="formInline.phone" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" @click="onSearch" icon="el-icon-search">搜 索</el-button>
        <el-button size="small" type="default" @click="handleAdd" icon="el-icon-plus">添加司机
        </el-button>
        <!-- <el-button size="small" type="default" icon="el-icon-download">
                    <a style="color:#000;text-decoration: none;" href="/muban/sijidaoru.xlsx"
            download="司机导入模板.xlsx">下载模板</a>
                  </el-button> -->
        <el-button size="small" type="default" icon="el-icon-download">
          <a style="color: rgb(61, 31, 32);text-decoration: none;" @click="exportReport($event)" href=""
            download="司机导入模板.xlsx">下载模板</a>
        </el-button>
        <el-button size="small" type="default" @click="uploadDialogVisible = true" icon="el-icon-upload2">导入司机
        </el-button>

        <el-button size="small" type="default" icon="el-icon-download">
          <a style="color: rgb(61, 31, 32);text-decoration: none;" @click="exportData($event)" href=""
            download="司机报表.xlsx">导出报表</a>
        </el-button>
      </el-form-item>
    </el-form>
    <el-table :data="tableData" style="margin-top:30px" row-key="truck_id" :tree-props="{ children: 'children' }"
      reserve-selection="true">
      <!-- :formatter="formatTruckCard" -->
      <el-table-column prop="driver_name" label="司机名称"></el-table-column>
      <el-table-column prop="phone" label="联系方式"></el-table-column>
      <el-table-column prop="dept_names" label="所属DC" :formatter="formatDept"></el-table-column>
      <el-table-column prop="truck_card" label="车牌号"></el-table-column>
      <el-table-column prop="truck_type_name" label="车辆类型"></el-table-column>
      <el-table-column prop="load_range_max" label="载重量（吨）"></el-table-column>
      <el-table-column label="驾驶证">
        <template slot-scope="scope">
          <!-- 图片文件 -->
          <el-image v-if="scope.row.drivers_license_pic_pdf == 'img'" class="img-table"
            :src="scope.row.drivers_license_pic" :preview-src-list="[scope.row.drivers_license_pic]">
          </el-image>
          <!-- pdf文件 -->
          <a :href="scope.row.drivers_license_pic" target="_blank" v-if="scope.row.drivers_license_pic_pdf == 'pdf'">
            <img src="../../assets/images/pdf.png" class="img-table" alt="">
          </a>

          <span v-if="scope.row.drivers_license_pic == ''">未上传</span>
        </template>
      </el-table-column>
      <el-table-column label="行驶证">
        <template slot-scope="scope">
          <!-- 图片文件 -->
          <el-image v-if="scope.row.driving_permit_pic_pdf == 'img'" class="img-table"
            :src="scope.row.driving_permit_pic" :preview-src-list="[scope.row.driving_permit_pic]">
          </el-image>
          <!-- pdf文件 -->
          <a :href="scope.row.driving_permit_pic" target="_blank" v-if="scope.row.driving_permit_pic_pdf == 'pdf'">
            <img src="../../assets/images/pdf.png" class="img-table" alt="">
          </a>

          <span v-if="scope.row.driving_permit_pic == ''">未上传</span>
        </template>
      </el-table-column>
      <el-table-column label="保险单">
        <template slot-scope="scope">
          <!-- 图片文件 -->
          <el-image v-if="scope.row.policy_pic_pdf == 'img'" class="img-table" :src="scope.row.policy_pic"
            :preview-src-list="[scope.row.policy_pic]">
          </el-image>
          <!-- pdf文件 -->
          <a :href="scope.row.policy_pic" target="_blank" v-if="scope.row.policy_pic_pdf == 'pdf'">
            <img src="../../assets/images/pdf.png" class="img-table" alt="">
          </a>

          <span v-if="scope.row.policy_pic == ''">未上传</span>
        </template>
      </el-table-column>
      <el-table-column label="身份证（正面）">
        <template slot-scope="scope">
          <!-- 图片文件 -->
          <el-image v-if="scope.row.id_card_front_pic_pdf == 'img'" class="img-table" :src="scope.row.id_card_front_pic"
            :preview-src-list="[scope.row.id_card_front_pic]">
          </el-image>
          <!-- pdf文件 -->
          <a :href="scope.row.id_card_front_pic" target="_blank" v-if="scope.row.id_card_front_pic_pdf == 'pdf'">
            <img src="../../assets/images/pdf.png" class="img-table" alt="">
          </a>

          <span v-if="scope.row.id_card_front_pic == ''">未上传</span>
        </template>
      </el-table-column>
      <el-table-column label="身份证（反面）">
        <template slot-scope="scope">
          <!-- 图片文件 -->
          <el-image v-if="scope.row.id_card_contrary_pic_pdf == 'img'" class="img-table"
            :src="scope.row.id_card_contrary_pic" :preview-src-list="[scope.row.id_card_contrary_pic]">
          </el-image>
          <!-- pdf文件 -->
          <a :href="scope.row.id_card_contrary_pic" target="_blank" v-if="scope.row.id_card_contrary_pic_pdf == 'pdf'">
            <img src="../../assets/images/pdf.png" class="img-table" alt="">
          </a>

          <span v-if="scope.row.id_card_contrary_pic == ''">未上传</span>
        </template>
      </el-table-column>
      <el-table-column label="安全承诺书">
        <template slot-scope="scope">
          <!-- 图片文件 -->
          <el-image v-if="scope.row.safety_book_pic_pdf == 'img'" class="img-table" :src="scope.row.safety_book_pic"
            :preview-src-list="[scope.row.safety_book_pic]">
          </el-image>
          <!-- pdf文件 -->
          <a :href="scope.row.safety_book_pic" target="_blank" v-if="scope.row.safety_book_pic_pdf == 'pdf'">
            <img src="../../assets/images/pdf.png" class="img-table" alt="">
          </a>

          <span v-if="scope.row.safety_book_pic == ''">未上传</span>
        </template>
      </el-table-column>
      <el-table-column label="检查表">
        <template slot-scope="scope">
          <el-image v-if="scope.row.check_table_pic_pdf == 'img'" class="img-table" :src="scope.row.check_table_pic"
            :preview-src-list="[scope.row.check_table_pic]">
          </el-image>
          <!-- pdf文件 -->
          <a :href="scope.row.check_table_pic" target="_blank" v-if="scope.row.check_table_pic_pdf === 'pdf'">
            <img src="../../assets/images/pdf.png" class="img-table" alt="">
          </a>

          <span v-if="scope.row.check_table_pic == ''">未上传</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" :width="350" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="default" @click="handleEdit(scope.$index, scope.row)"
            v-if="scope.row.driver_name != undefined">编辑</el-button>
          <el-button size="mini" type="primary" @click="handleDelete(scope.$index, scope.row)"
            v-if="scope.row.driver_name != undefined">删除</el-button>
          <el-button size="mini" type="default" @click="handleEditTruck(scope.$index, scope.row)"
            v-if="scope.row.driver_name == undefined">编辑车辆</el-button>
          <el-button size="mini" type="primary" @click="handleDeleteTruck(scope.$index, scope.row)"
            v-if="scope.row.driver_name == undefined">删除车辆</el-button>
          <el-button size="mini" type="primary" @click="handleAddTruck(scope.$index, scope.row)"
            v-if="scope.row.driver_name != undefined">添加车辆</el-button>
          <el-button size="mini" type="primary" @click="handleAddImg(scope.$index, scope.row)">上传资料</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @current-change="handleCurrentChange" :current-page="formInline.page" :page-size="formInline.limit"
      :hide-on-single-page="true" layout="total, prev, pager, next" :total="total">
    </el-pagination>
    <el-dialog :title="dialogTitle" :visible.sync="addDialogVisible" width="40%" center :before-close="beforeClose"
      custom-class="center_dislog">
      <el-form ref="editForm" :model="editForm" label-width="80px" :rules="addRules">
        <!-- 司机姓名 -->
        <el-form-item label="司机姓名" prop="driver_name">
          <el-input v-model="editForm.driver_name" placeholder="请输入"></el-input>
        </el-form-item>
        <!-- 联系方式 -->
        <el-form-item label="联系方式" prop="phone">
          <el-input type="tel" v-model="editForm.phone" placeholder="请输入"></el-input>
        </el-form-item>
        <!-- 车牌号 -->
        <el-form-item label="车牌号" prop="truck_card">
          <el-input v-model="editForm.truck_card" placeholder="请输入"></el-input>
        </el-form-item>
        <!-- 车辆类型 -->
        <el-form-item label="车辆类型" prop="truck_type">
          <el-select v-model="editForm.truck_type" placeholder="请选择" filterable>
            <el-option v-for="(item, index) in driverGround" :key="index" :label="item.name" :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 载重量 -->
        <el-form-item label="载重量" prop="load_range_max">
          <el-input v-model="editForm.load_range_max" placeholder="吨"></el-input>
        </el-form-item>
        <!--  选择Dc-->
        <el-form-item label="所属DC" prop="dc_ids">
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll"
            @change="handleCheckAllChange">全部</el-checkbox>
          <div style="margin: 15px 0;"></div>
          <el-checkbox-group v-model="editForm.dc_ids" @change="handleCheckedChange">
            <el-checkbox v-for="item in DCData" :label="item.id" :key="item.id">{{ item.title }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="beforeClose">取 消</el-button>
        <el-button type="primary" :disabled="isDisabled" @click="addSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- //导入报表 -->
    <el-dialog title="导入司机" :visible.sync="uploadDialogVisible" width="40%" center custom-class="center_dislog"
      :before-close="claoseUploadFile">
      <el-upload ref="uploadFile" action="#" accept=".xlsx" :limit="1" :auto-upload="false" :on-remove="handleRemove"
        :http-request="uploadFile">
        <el-button icon="el-icon-plus" size="small" type="primary">选择文件
        </el-button>
        <div slot="tip" class="el-upload__tip">请上传xlsx格式的文件</div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="claoseUploadFile" size="small">取消</el-button>
        <el-button type="primary" :disabled="addDisabled" @click="uploadSubmit" size="small">
          上传</el-button>
      </span>
    </el-dialog>

    <el-dialog :title="dialogTitleTruck" :visible.sync="addDialogVisibleTruck" width="40%" center
      :before-close="beforeCloseTruck" custom-class="center_dislog">
      <el-form ref="truckForm" :model="truckForm" label-width="80px" :rules="addRulesTruck">
        <!-- 车牌号 -->
        <el-form-item label="车牌号" prop="truck_card">
          <el-input v-model="truckForm.truck_card" placeholder="请输入"></el-input>
        </el-form-item>
        <!-- 车辆类型 -->
        <el-form-item label="车辆类型" prop="truck_type">
          <el-select v-model="truckForm.truck_type" placeholder="请选择" filterable>
            <el-option v-for="(item, index) in driverGround" :key="index" :label="item.name" :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 载重量 -->
        <el-form-item label="载重量" prop="load_range_max">
          <el-input v-model="truckForm.load_range_max" placeholder="吨"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="beforeCloseTruck">取 消</el-button>
        <el-button type="primary" :disabled="isDisabledTruck" @click="addSubmitTruck">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 上传图片资料 -->
    <el-dialog title="上传资料" :visible.sync="addImgData" width="40%" center :before-close="beforeCloseAddImg"
      custom-class="center_dislog">
      <el-form ref="imageArr" :model="imageArr" :inline="true">
        <el-form-item label="" prop="drivers_license_pic">
          <div class="title-s">驾驶证</div>
          <i class="el-icon-circle-close" v-if="imageArr.drivers_license_pic"
            @click.stop="deleteImg('drivers_license_pic')"></i>
          <el-upload class="avatar-uploader" list-type="picture" drag action="#"
            :on-change="(file) => handleChangeUpload(file, 'drivers_license_pic')" :show-file-list="false"
            :auto-upload="false">
            <div v-if="imageArr.drivers_license_pic" class="up-img-box">
              <img :src="imageArr.drivers_license_pic" class="avatar">
              <!-- <i class="el-icon-circle-close" @click.stop="deleteImg('drivers_license_pic')"></i> -->
            </div>
            <div v-else class="upload-icon">
              <img src="../../assets/images/upload-img.png" alt="">
              <div>点击上传，或将文件拖拽到此处，大小在10M内。</div>
            </div>
          </el-upload>
        </el-form-item>

        <el-form-item label="" prop="driving_permit_pic">
          <div class="title-s">行驶证</div>
          <i class="el-icon-circle-close" v-if="imageArr.driving_permit_pic"
            @click.stop="deleteImg('driving_permit_pic')"></i>
          <el-upload class="avatar-uploader" drag action="#"
            :on-change="(file) => handleChangeUpload(file, 'driving_permit_pic')" :show-file-list="false"
            :auto-upload="false">
            <div v-if="imageArr.driving_permit_pic" class="up-img-box">
              <img :src="imageArr.driving_permit_pic" class="avatar">
              <!-- <i class="el-icon-delete" @click.stop="deleteImg('driving_permit_pic')"></i> -->
            </div>

            <div v-else class="upload-icon">
              <img src="../../assets/images/upload-img.png" alt="">
              <div>点击上传，或将文件拖拽到此处，大小在10M内。</div>
            </div>
          </el-upload>
        </el-form-item>

        <el-form-item label="" prop="policy_pic">
          <div class="title-s">保险单</div>
          <i class="el-icon-circle-close" v-if="imageArr.policy_pic" @click.stop="deleteImg('policy_pic')"></i>
          <el-upload class="avatar-uploader" drag action="#"
            :on-change="(file) => handleChangeUpload(file, 'policy_pic')" :show-file-list="false" :auto-upload="false">
            <div v-if="imageArr.policy_pic" class="up-img-box">
              <img :src="imageArr.policy_pic" class="avatar">
              <!-- <i class="el-icon-delete" @click.stop="deleteImg('policy_pic')"></i> -->
            </div>
            <div v-else class="upload-icon">
              <img src="../../assets/images/upload-img.png" alt="">
              <div>点击上传，或将文件拖拽到此处，大小在10M内。</div>
            </div>
          </el-upload>
        </el-form-item>

        <el-form-item label="" prop="safety_book_pic">
          <div class="title-s">安全承诺书</div>
          <i class="el-icon-circle-close" v-if="imageArr.safety_book_pic"
            @click.stop="deleteImg('safety_book_pic')"></i>
          <el-upload class="avatar-uploader" drag action="#"
            :on-change="(file) => handleChangeUpload(file, 'safety_book_pic')" :show-file-list="false"
            :auto-upload="false">
            <div v-if="imageArr.safety_book_pic" class="up-img-box">
              <img :src="imageArr.safety_book_pic" class="avatar">
              <!-- <i class="el-icon-delete " @click.stop="deleteImg('safety_book_pic')"></i> -->
            </div>
            <div v-else class="upload-icon">
              <img src="../../assets/images/upload-img.png" alt="">
              <div>点击上传，或将文件拖拽到此处，大小在10M内。</div>
            </div>
          </el-upload>
        </el-form-item>

        <el-form-item label="" prop="check_table_pic">
          <div class="title-s">检查表</div>
          <i class="el-icon-circle-close" v-if="imageArr.check_table_pic"
            @click.stop="deleteImg('check_table_pic')"></i>
          <el-upload class="avatar-uploader" drag action="#"
            :on-change="(file) => handleChangeUpload(file, 'check_table_pic')" :show-file-list="false"
            :auto-upload="false">
            <div v-if="imageArr.check_table_pic" class="up-img-box">
              <img :src="imageArr.check_table_pic" class="avatar">
              <!-- <i class="el-icon-delete" @click.stop="deleteImg('check_table_pic')"></i> -->
            </div>
            <div v-else class="upload-icon">
              <img src="../../assets/images/upload-img.png" alt="">
              <div>点击上传，或将文件拖拽到此处，大小在10M内。</div>
            </div>
          </el-upload>
        </el-form-item>

        <div style="width: 210px;"></div>

        <el-form-item label="" prop="id_card_front_pic">
          <div class="title-s">身份证正面（国徽）</div>
          <i class="el-icon-circle-close" v-if="imageArr.id_card_front_pic"
            @click.stop="deleteImg('id_card_front_pic')"></i>
          <el-upload class="avatar-uploader" drag action="#"
            :on-change="(file) => handleChangeUpload(file, 'id_card_front_pic')" :show-file-list="false"
            :auto-upload="false">
            <div v-if="imageArr.id_card_front_pic" class="up-img-box">
              <img :src="imageArr.id_card_front_pic" class="avatar">
              <!-- <i class="el-icon-delete" @click.stop="deleteImg('id_card_front_pic')"></i> -->
            </div>
            <div v-else class="upload-icon">
              <img src="../../assets/images/upload-img.png" alt="">
              <div>点击上传，或将文件拖拽到此处，大小在10M内。</div>
            </div>
          </el-upload>
        </el-form-item>

        <el-form-item label="" prop="id_card_contrary_pic">
          <div class="title-s">身份证反面（人像）</div>
          <i class="el-icon-circle-close" v-if="imageArr.id_card_contrary_pic"
            @click.stop="deleteImg('id_card_contrary_pic')"></i>
          <el-upload class="avatar-uploader" drag action="#"
            :on-change="(file) => handleChangeUpload(file, 'id_card_contrary_pic')" :show-file-list="false"
            :auto-upload="false">
            <div v-if="imageArr.id_card_contrary_pic" class="up-img-box">
              <img :src="imageArr.id_card_contrary_pic" class="avatar">
              <!-- <i class="el-icon-delete" @click.stop="deleteImg('id_card_contrary_pic')"></i> -->
            </div>
            <div v-else class="upload-icon">
              <img src="../../assets/images/upload-img.png" alt="">
              <div>点击上传，或将文件拖拽到此处，大小在10M内。</div>
            </div>
          </el-upload>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="beforeCloseAddImg">取 消</el-button>
        <el-button type="primary" :disabled="isDisabledImg" @click="addSubmitImg">确 定</el-button>
      </span>
    </el-dialog>

  </el-main>
</template>
<script>
import {
  mapState
} from 'vuex'
import {
  getDriverList,
  addDriver,
  editDriver,
  deleteDriver,
  uploadDriver,
  getAllDc,
  getTruck,
  addTruckA,
  editTruckA,
  deleteTruck,
  addDriverMateriaUpload
} from '../../api.js'
export default {
  name: "factoryDriver",
  data() {
    var validatePass = (rule, value, callback) => {

      if (value && (!(/^[1][3456789]\d{9}$/).test(value) || !(/^[1-9]\d*$/).test(value) || value.length !== 11)) {
        callback(new Error('请输入正确的手机号'))
      } else if (value == '') {
        callback(new Error('请输入手机号'))
      } else {
        callback()
      }
    };
    var truckType = (rule, value, callback) => {
      // 豫ADN6672
      // 新能源和燃油车
      let xny = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$/;
      // 燃油车
      let ryc = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/
      if (value == "") {
        callback(new Error("请输入车牌号"))
      } else if (!xny.test(value)) {
        callback(new Error("请输入正确的车牌号"))
      } else {
        callback()
      }
    }
    return {
      isAdd: true,
      isDisabled: false,
      addDisabled: false,
      addDialogVisible: false,
      addDialogVisibleTruck: false,
      addImgData: false,
      // 显示的图片
      imageArr: {
        check_table_pic: '',
        safety_book_pic: '',
        id_card_contrary_pic: '',
        id_card_front_pic: '',
        policy_pic: '',
        driving_permit_pic: '',
        drivers_license_pic: '',
      },
      // 上传的图片
      unpImageArr: {
        check_table_pic: '',
        safety_book_pic: '',
        id_card_contrary_pic: '',
        id_card_front_pic: '',
        policy_pic: '',
        driving_permit_pic: '',
        drivers_license_pic: '',
      },
      // 删除的图片
      deleteImageArr: {
        check_table_pic: '',
        safety_book_pic: '',
        id_card_contrary_pic: '',
        id_card_front_pic: '',
        policy_pic: '',
        driving_permit_pic: '',
        drivers_license_pic: '',
      },
      isDisabledImg: false,


      uploadDialogVisible: false,
      isDisabledTruck: false,
      imageUrl: '',
      dialogTitle: '',
      breadcrumbName: '',
      breadcrumbPath: '',
      breadcrumbNameP: '',
      tableData: [],
      deptData: [],
      DCData: [],
      isIndeterminate: false,
      checkAll: false,
      driverGround: [],
      dialogTitleTruck: '',
      //查询栏默认展示数据
      formInline: {
        driver_name: '',
        phone: '',
        dept_id: '',
        page: 1,
        limit: 5
      },
      editForm: {
        driver_name: '',
        phone: '',
        truck_card: '',
        truck_type: '',
        load_range_max: '',
        dc_ids: [],
      },
      truckForm: {
        id: '',
        driver_id: '',
        truck_card: '',
        truck_type: '',
        load_range_max: '',
      },
      //分页
      total: 0,
      addRules: {
        driver_name: [{
          required: true,
          message: '请输入司机名称',
          trigger: 'blur'
        }],
        truck_type: [{
          required: true,
          message: '请选择车辆类型',
          trigger: 'blur'
        }],
        // phone: [{
        //   required: true,
        //   trigger: 'blur',
        //   validator: validatePass,
        // }],
        // truck_card: [{
        //   required: false,
        //   trigger: 'blur',
        //   validator: truckType
        // }],
        load_range_max: [{
          required: true,
          message: '请输入载重量',
          trigger: 'blur'
        }],
        dc_ids: [{
          required: true,
          message: '请选择所属DC',
          trigger: 'blur'
        }],
      },
      addRulesTruck: {
        truck_type: [{
          required: true,
          message: '请选择车辆类型',
          trigger: 'blur'
        }],
        // truck_card: [{
        //   validator: truckType,
        //   trigger: 'blur'
        // }],
        // load_range_max:[{
        //   required: true,
        //   message: '请输入载重量',
        //   trigger: 'blur'
        // }],
      },
      isTruckAdd: true,
      itemData: {},

    }
  },
  async mounted() {
    this.breadcrumbName = this.$route.query.breadcrumbName
    this.breadcrumbPath = this.$route.query.breadcrumbPath
    this.breadcrumbNameP = this.$route.query.breadcrumbNameP
    this.driverGround = await this.common.getCode(this.baseUrl, 'truck_type', this.Token)
    this.getDeptList();
    this.getAllDcInfo();
    this.getTableDate(this.formInline)
  },
  methods: {
    getDeptList() {
      getAllDc({}).then(res => {
        if (res.ErrorCode == 0) {
          this.deptData = res.Data.list
        } else {
          this.$message.error(res.ErrorMsg)
        }
      })
    },
    getAllDcInfo() {
      getAllDc().then(res => {
        if (res.ErrorCode == 0) {
          this.DCData = res.Data.list
          // console.log(this.DCData)
        } else {
          this.$message.error(res.ErrorMsg);
        }
      })
    },
    //获取司机列表
    getTableDate(searchObj) {
      getDriverList(searchObj).then(res => {
        if (res.ErrorCode == 0) {
          this.tableData = res.Data.list
          this.total = res.Data.total

          //判断文件类型 pdf或者图片
          this.tableData.forEach((item, index) => {
            if (item.drivers_license_pic != '') {
              item.drivers_license_pic_pdf = this.pdfOFimg(item.drivers_license_pic)
            } else {
              item.drivers_license_pic_pdf = ''
            }

            if (item.driving_permit_pic != '') {
              item.driving_permit_pic_pdf = this.pdfOFimg(item.driving_permit_pic)
            } else {
              item.driving_permit_pic_pdf = ''
            }

            if (item.policy_pic != '') {
              item.policy_pic_pdf = this.pdfOFimg(item.policy_pic)
            } else {
              item.policy_pic_pdf = ''
            }

            if (item.id_card_front_pic != '') {
              item.id_card_front_pic_pdf = this.pdfOFimg(item.id_card_front_pic)
            } else {
              item.id_card_front_pic_pdf = ''
            }

            if (item.id_card_contrary_pic != '') {
              item.id_card_contrary_pic_pdf = this.pdfOFimg(item.id_card_contrary_pic)
            } else {
              item.id_card_contrary_pic_pdf = ''
            }

            if (item.safety_book_pic != '') {
              item.safety_book_pic_pdf = this.pdfOFimg(item.safety_book_pic)
            } else {
              item.safety_book_pic = ''
            }

            if (item.check_table_pic != '') {
              item.check_table_pic_pdf = this.pdfOFimg(item.check_table_pic)
            } else {
              item.check_table_pic_pdf = ''
            }
          })
        } else {
          this.$message.error(res.ErrorMsg);
        }
      })
    },
    pdfOFimg(url) {
      if (url.substring(url.lastIndexOf('.') + 1) == 'pdf') {
        return 'pdf'
      } else {
        return 'img'
      }
    },
    // 添加 
    handleAdd() {
      this.isAdd = true
      this.addDialogVisible = true;
      this.dialogTitle = '添加';
      for (var k in this.editForm) {
        if (k == 'dc_ids') {
          this.editForm[k] = []
        } else {
          this.editForm[k] = ''
        }
      }
      console.log(this.editForm)
    },
    // 上传资料
    handleAddImg(index, row) {
      this.itemData = row;
      this.addImgData = true;
      for (let i in this.imageArr) {
        if (this.pdfOFimg(row[i]) == 'pdf') {
          this.imageArr[i] = require('../../assets/images/pdf.png')
        } else {
          this.imageArr[i] = row[i]
        }
        this.unpImageArr[i] = row[i]
      }
    },
    //添加车辆
    handleAddTruck(index, row) {
      console.log("row", row)
      this.isTruckAdd = true
      // this.truckForm.id = row.truck_id
      this.truckForm.driver_id = row.driver_id
      this.dialogTitleTruck = "添加车辆"
      this.addDialogVisibleTruck = true;
    },
    handleEditTruck(index, row) {
      this.dialogTitleTruck = "编辑车辆"
      this.isTruckAdd = false
      this.truckForm.id = row.truck_id
      this.truckForm.driver_id = row.driver_id
      this.truckForm.truck_card = row.truck_card
      this.truckForm.truck_type = row.truck_type + ''
      this.truckForm.load_range_max = row.load_range_max
      this.addDialogVisibleTruck = true;
    },
    //编辑
    handleEdit(index, row) {
      this.isAdd = false
      this.dialogTitle = '编辑';
      this.editForm.id = row.driver_id;
      this.editForm.truck_id = row.truck_id;
      this.editForm.driver_name = row.driver_name
      this.editForm.phone = row.phone
      this.editForm.truck_card = row.truck_card;
      this.editForm.truck_type = row.truck_type + '';
      this.editForm.load_range_max = row.load_range_max
      this.editForm.dc_ids = row.dept_ids
      this.addDialogVisible = true;
    },
    //表格分页
    handleCurrentChange(val) {
      this.formInline.page = val;
      this.getTableDate(this.formInline)
    },
    //表格查询
    onSearch() {
      this.formInline.page = 1;
      this.getTableDate(this.formInline)
    },
    //删除车辆
    handleDeleteTruck(index, row) {
      var _this = this
      _this.$confirm('此操作將刪除该数据, 是否继续？', '提 示', {
        confirmButtonText: '确 定',
        cancelButtonText: '取 消',
        center: true
      }).then(() => {
        var data = {
          id: row.truck_id,
        }
        deleteTruck(data).then(res => {
          if (res.ErrorCode == 0) {
            _this.getTableDate(_this.formInline);
            _this.$message.success("删除成功");
          } else {
            this.$message.error(res.ErrorMsg);
          }
        })
      }).catch(() => { });
    },
    //刪除
    handleDelete(index, row) {
      var _this = this
      _this.$confirm('此操作將刪除该数据, 是否继续？', '提 示', {
        confirmButtonText: '确 定',
        cancelButtonText: '取 消',
        center: true
      }).then(() => {
        var data = {
          id: row.driver_id,
        }
        deleteDriver(data).then(res => {
          if (res.ErrorCode == 0) {
            _this.getTableDate(_this.formInline);
            _this.$message.success("删除成功");
          } else {
            this.$message.error(res.ErrorMsg);
          }
        })
      }).catch(() => { });
    },
    addSubmitTruck() {
      var _this = this;
      this.$refs['truckForm'].validate((valid) => {
        console.log("valid", valid)
        if (valid) {
          _this.isDisabledTruck = true;
          var dataObj = JSON.parse(JSON.stringify(_this.truckForm));
          dataObj.truck_type = this.truckForm.truck_type * 1
          if (_this.isTruckAdd) {
            addTruckA(dataObj).then(res => {
              if (res.ErrorCode == 0) {
                _this.$message.success(res.ErrorMsg);
                _this.getTableDate(_this.formInline);
                _this.isDisabledTruck = false;
                _this.beforeCloseTruck();
              } else {
                _this.isDisabledTruck = false;
                this.$message.error(res.ErrorMsg);
              }
            })
          } else {
            editTruckA(dataObj).then(res => {
              if (res.ErrorCode == 0) {
                _this.$message.success(res.ErrorMsg);
                _this.getTableDate(_this.formInline);
                _this.isDisabledTruck = false;
                _this.beforeCloseTruck();
              } else {
                _this.isDisabledTruck = false;
                this.$message.error(res.ErrorMsg);
              }
            })
          }
        }
      })
    },

    //提交
    addSubmit() {
      this.$refs['editForm'].validate((valid) => {
        if (valid) {
          var _this = this;
          _this.isDisabled = true;
          var dataObj = JSON.parse(JSON.stringify(_this.editForm));
          dataObj.truck_type = this.editForm.truck_type * 1
          dataObj.dc_ids = this.editForm.dc_ids.join(",")
          if (_this.isAdd) {
            addDriver(dataObj).then(res => {
              if (res.ErrorCode == 0) {
                _this.$message.success("添加成功");
                _this.getTableDate(_this.formInline);
                _this.isDisabled = false;
                _this.beforeClose();
              } else {
                _this.isDisabled = false;
                this.$message.error(res.ErrorMsg);
              }
            })
          } else {
            editDriver(dataObj).then(res => {
              if (res.ErrorCode == 0) {
                _this.$message.success("编辑成功");
                _this.isDisabled = false;
                _this.getTableDate(_this.formInline);
                _this.beforeClose();
              } else {
                _this.isDisabled = false;
                this.$message.error(res.ErrorMsg);
              }
            })
          }
        }
      })
    },

    beforeClose() {
      console.log("this.$refs.editForm", this.$refs.editForm)
      this.addDialogVisible = false
      this.isIndeterminate = false,
        this.checkAll = false,
        this.$refs.editForm.resetFields();
    },
    beforeCloseTruck() {
      this.addDialogVisibleTruck = false
      this.$refs.truckForm.resetFields();
    },
    formatNorm(row, column, cellValue) {
      return row.loadRangeMin + '~' + row.loadRangeMax
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    //导入
    uploadSubmit() {
      this.$refs.uploadFile.submit();
    },
    uploadFile(file) {
      const m2 = file.size / 1024 / 1024
      if (m2 > 2) {
        this.$message.error(this.language.prompt_select_xls_file_alert2);
        this.handleRemove()
        return false
      }
      // 根据后台需求数据格式
      const form = new FormData();
      // 文件对象  
      form.append("file", file.file);
      uploadDriver(form).then(res => {
        if (res.ErrorCode == 0) {
          this.getTableDate(this.formInline);
          this.$message.success("导入成功");
          this.$refs.uploadFile.clearFiles();
          this.uploadDialogVisible = false
        } else {
          this.$message.error(res.ErrorMsg);
        }
      })
    },
    exportReport(e) {
      e.target.href = this.baseUrl + 'report/export/driver_download_xlsx?code=driver' +
        '&access_token=' + this.Token
    },
    // 导出报表
    exportData(e) {
      e.target.href = this.baseUrl + 'report/export/driver_report_export?access_token=' + this.Token
    },
    handleCheckAllChange(val) {
      var dataArr = [];
      for (let i in this.DCData) {
        dataArr.push(this.DCData[i].id)
      }
      this.editForm.dc_ids = val ? dataArr : [];
      this.isIndeterminate = false;
    },
    handleCheckedChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.DCData.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.DCData.length;
      // console.log("this.editForm.", this.editForm)
    },
    claoseUploadFile() {
      this.$refs.uploadFile.clearFiles();
      this.uploadDialogVisible = false
    },
    onBeforeUpload(file) {
      const isJPG =
        file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG, PNG, JPEG格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    // 关闭上传图片资料弹框
    beforeCloseAddImg() {
      this.addImgData = false;
      this.itemData = {};
      for (let i in this.imageArr) {
        this.imageArr[i] = ""
      }
      for (let i in this.deleteImageArr) {
        this.deleteImageArr[i] = ""
      }
      // console.log(this.imageArr)
    },
    // 删除图片
    deleteImg(name) {
      // console.log(name)
      this.deleteImageArr[name] = '-1'
      this.imageArr[name] = ''
    },
    // 上传图片
    handleChangeUpload(file, name) {
      // console.log(name)
      let isJPG = false
      let isLt2M = file.size / 1024 / 1024 < 10;
      console.log(123, file.raw.type)
      if (file.raw.type === 'image/jpg' || file.raw.type === 'image/jpeg' || file.raw.type === 'image/png' || file.raw.type ===
        'image/JPG' || file.raw.type === 'image/JPEG' || file.raw.type === 'application/pdf') {
        isJPG = true
      }
      if (!isJPG) {
        this.$message.error('请上传 jpg、jpeg、png、JPG、JPEG格式的图片或者pdf文件！');
        return;
      }
      // if (!isLt2M) {
      //   this.$message.error('上传图片大小不能超过 10MB！');
      //   return;
      // }
      // this.imageArr[name] = URL.createObjectURL(file.raw);
      this.getBase64(file.raw).then(res => {
        if (file.raw.type === 'application/pdf') {
          this.imageArr[name] = require('../../assets/images/pdf.png');
        } else {
          this.imageArr[name] = res;
        }
        this.unpImageArr[name] = res;
        this.deleteImageArr[name] = '';
      });
    },
    getBase64(file) {
      return new Promise(function (resolve, reject) {
        let reader = new FileReader();
        let imgResult = "";
        reader.readAsDataURL(file);
        reader.onload = function () {
          imgResult = reader.result;
        };
        reader.onerror = function (error) {
          reject(error);
        };
        reader.onloadend = function () {
          resolve(imgResult);
        };
      });
    },
    // 提交图片资料
    addSubmitImg() {
      var _this = this;
      _this.isDisabledImg = true;
      let reqData = {};
      for (let i in _this.unpImageArr) {
        // 判断图片是否删除
        if (this.deleteImageArr[i] == '-1') {
          reqData[i] = '-1'
        } else {
          if (_this.unpImageArr[i] == _this.itemData[i]) {
            reqData[i] = ''
          } else {
            reqData[i] = _this.unpImageArr[i]
          }
        }

      }
      reqData.driver_id = _this.itemData.driver_id
      reqData.truck_id = _this.itemData.truck_id
      addDriverMateriaUpload(reqData).then(res => {
        if (res.ErrorCode == 0) {
          _this.$message.success(res.ErrorMsg);
          _this.getTableDate(_this.formInline);
          _this.isDisabledImg = false;
          _this.beforeCloseAddImg();
        } else {
          _this.isDisabledImg = false;
          this.$message.error(res.ErrorMsg);
        }
      })
    },

    formatDept(row, column, cellValue) {
      return Array.prototype.join.call(cellValue, '，');
    },
  },
  computed: {
    ...mapState({
      baseUrl: state => state.baseUrl,
      Token: state => state.access_token,
    }),
  },
}
</script>

<style scoped>
main>>>.el-icon-date {
  right: -30px;
}

main>>>.el-date-editor.el-input.el-date-editor--date {
  width: 100%;
}

.tips {
  color: #f56c6c;
  font-size: 12px;
}

main>>>.el-form-item__content {
  line-height: 24px;
}

.avatar-uploader>>>.el-upload {
  width: 216px;
  height: 140px;
  background: #FFF9F8;
  border-radius: 2px;
  border: 1px dashed #CCCCCC;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader>>>.el-upload-dragger {
  width: 100%;
  height: 100%;
  background: #FFF9F8;
  border-radius: 2px;
  border: 1px dashed #CCCCCC;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 216px;
  height: 140px;
}

.up-img-box {
  position: relative;
}

.el-icon-delete {
  position: absolute;
  top: 5px;
  right: 5px;
  font-size: 25px;
  color: #000;
}

.el-icon-circle-close {
  position: absolute;
  top: 15px;
  right: -8px;
  font-size: 25px;
  color: #000;
  z-index: 999;
}

.upload-icon {
  padding-top: 40px;
}

.title-s {
  margin-bottom: 5px;
}

.img-table {
  width: 50px;
  height: 50px;
}
</style>